import axios from 'axios'
import {Toast} from 'mint-ui'

axios.interceptors.request.use(config => {
  return config
}, err => {
  Toast('请求超时!')
})
axios.interceptors.response.use(data => {
  if (data.status && data.status == 200 && data.data.status == 500) {
    Toast(data.data.msg)
    return
  }
  return data
}, err => {
  if (err.response.status == 504 || err.response.status == 404) {
    Toast('服务器被吃了⊙﹏⊙')
    // Message.error({message: '服务器被吃了⊙﹏⊙∥'});
  } else if (err.response.status == 403) {
    Toast('权限不足,请联系管理员!')
  } else if (err.response.status == 401) {
    Toast(err.response.data.msg)
  } else {
    if (err.response.data.msg) {
      Toast(err.response.data.msg)
    } else {
      Toast('未知错误!')
    }
  }
})
let base = '/api/'
export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: JSON.stringify(params),
    headers: {
      'Content-Type': 'application/json'
    }
  })
}
export const uploadFileRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: JSON.stringify(params),
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
export const putRequest = (url, params) => {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: JSON.stringify(params),
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}
export const deleteRequest = (url) => {
  return axios({
    method: 'delete',
    url: `${base}${url}`
  })
}
export const getRequest = (url) => {
  return axios({
    method: 'get',
    url: `${base}${url}`
  })
}
